
export const compressImgNew = (file,quality) => {
    return new Promise(resolve => {
        const reader = new FileReader()
        const image = new Image()
        image.onload = (imageEvent) => {
            const canvas = document.createElement('canvas') // 创建画布
            const context = canvas.getContext('2d')         // 画布为2d
            const width = image.width     // 图片宽度 / 压缩比例
            const height = image.height   // 图片高度 / 压缩比例
            canvas.width = width                            // 画布宽度
            canvas.height = height                          // 画布宽度
            context.clearRect(0, 0, width, height)
            context.drawImage(image, 0, 0, width, height)
            
            const dataUrl = canvas.toDataURL(file.type,quality)     //图片转路径
            const blobData = dataURLtoBlob(dataUrl, file.type) //图片转二进制
            resolve(blobData)
        }
        reader.onload = e => { image.src = e.target.result }
        reader.readAsDataURL(file)
    })
};

//图片转二进制
function dataURLtoBlob(dataUrl, type) {
    var binary = atob(dataUrl.split(',')[1])
    var array = []
    for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i))
    }
    return new Blob([new Uint8Array(array)], { type: type })
}
